<?php
class BaseController extends Zend_Controller_Action {
	protected $controller_url;
	protected $name;
	protected $db;
	protected $_auth;
	protected $_site;
	protected $configs = array();
	protected $configs_app = array();
	protected $configFile;
	protected $_layout;
	protected $_redirector;
	protected $_flashMessenger;
	protected $_logged = NULL;
	protected $cache;
	protected $_layoutPath = 'third';
	
	public function init( ) {
		
		
		$this->view->base_url = '/' . $this->getRequest ()->getBaseUrl ();
		
		//CONTROLLER URL
		$this->controller_url = $this->_request->getBaseUrl () . '/third/' . $this->name;
		$this->view->controller_url = $this->controller_url;
		
		// jQuery
		$this->view->addHelperPath ( 'ZendX/JQuery/View/Helper/', 'ZendX_JQuery_View_Helper' );
		
		//Configs
		$this->initConfigs ();
		
		//db
		$this->db = Zend_Registry::get ( 'db' );
		
		//cache
		$this->cache = Zend_Registry::get ( 'cache' );
		
		//auth
		$this->_auth = Zend_Registry::get ( 'auth' ); 
		
		//LOGGED USER
		$this->_logged = $this->_auth->getLogged();
		$this->view->assign('logged', $this->_logged );

		//LOAD SITE INFOS
		$this->_site = Zend_Registry::get('site');
		$this->view->assign('site', $this->_site );
		
		$template = $this->_site['template'];

		//LAYOUT OPTIONS
		$this->_layout = Zend_Layout::getMvcInstance ();
		$this->setLayout ();
		$this->setLayoutPath ( $this->_layoutPath );
		$this->disableLayoutInAjax ();
		
		//FLASH MESSAGES
		$this->_flashMessenger 	= $this->_helper->getHelper('FlashMessenger');
		
		//REDIRECTOR
		$this->_redirector = $this->_helper->getHelper('Redirector');
		
		//NAVIGATION
		$this->initNavigation();
		
		$this->_frontController = Zend_Controller_Front::getInstance();
	}

	protected function initNavigation(){
		if( $this->_auth->isLogged() ){ 
			$menu = new Third_Navigation( $this->_logged->nivel );

			// Directly
			$this->view-> navigation( $menu );
		}
	}

	protected function initConfigs() {
		if( !(defined('CONTROLLER_CONFIG_PATH')))
			define ( 'CONTROLLER_CONFIG_PATH', $this->getFrontController ()->getModuleDirectory () . '/configs/' );

		if ( file_exists ( CONTROLLER_CONFIG_PATH . $this->configFile . '.ini' )) {
			try {
				$this->configs_app = Zend_Registry::get('configs');
				
				// CONFIGS
				$configs = new Zend_Config_Ini ( CONTROLLER_CONFIG_PATH . $this->configFile . '.ini' );
				$this->configs = $configs;
			} catch ( Zend_Exception $e ) {
				Zend_Debug::dump ( $e->getMessage () );
			}
		}
	}
	
	protected function setLayoutPath( $path = 'third' ) {
		if(!defined('MODULE_LAYOUT_PATH')){
			define('MODULE_LAYOUT_PATH', $this->_layout->getLayoutPath () . $path );
			$this->_layout->setLayoutPath ( MODULE_LAYOUT_PATH );
		}
	}
	
	protected function setLayout($layoutScript = 'layout') {
		try {
			$this->_layout->setLayout ( $layoutScript );
		} catch ( Zend_Exception $e ) {
			Zend_Debug::dump ( $e->getMessage () );
		}
	}
	
	protected function disableViewRender(){
		$this->_helper->viewRenderer->setNoRender(true);
	}
	
	protected function disableLayoutInAjax() {
		//DESABILITA LAYOUT CASO A REQUISICAO SEJA AJAX
		if ( $this->getRequest()->isXmlHttpRequest() ) {
			$this->disableLayout ();
		}
	}
	
	public function disableLayout() {
		$this->_layout->disableLayout ();
	}
	
	public function isLogged() {
		$logged = $this->_auth->isLogged ();
		
		if ($logged) {
		
		}
	}
	
	protected function loadConfigFile($file, $secao) {
		if (file_exists ( CONTROLLER_CONFIG_PATH . $file ))
			return new Zend_Config_Ini ( CONTROLLER_CONFIG_PATH . $file, $secao );
		else
			return null;
	}
	
	protected function log( $tipo, $mensagem = NULL, $tabela = NULL, $tabela_objeto_id = NULL  ){

		$columnMapping = array(
			'mensagem' => 'message',
			'tipo'=>'tipo',
			'sites_id'=>'sites_id',
			'usuarios_id'=>'usuarios_id',
			'module' => 'module',
			'controller' => 'controller',
			'action' => 'action',
			'date'=>'date',
			'ip'=>'ip',
			'host'=>'host',
			'referer'=>'referer',
			'params'=>'params',
			'tabela'=>'tabela',
			'tabela_objeto_id'=>'tabela_objeto_id'
		);

		$userInfos = $this->getRequest()->getServer();

		$writer = new Zend_Log_Writer_Db($this->db, 'logs', $columnMapping);

		$logger = new Zend_Log( $writer );

		$referer = "";
		if(isset( $userInfos['HTTP_REFERER'] )){
			$referer = $userInfos['HTTP_REFERER'];
		}

		$logger->setEventItem('message', $mensagem );
		$logger->setEventItem('tipo', $tipo );
		$logger->setEventItem('sites_id', $this->_site['id']  );
		$logger->setEventItem('usuarios_id', $this->_auth->getLoggedId() );
		$logger->setEventItem('module', $this->getRequest()->getModuleName() );
		$logger->setEventItem('controller', $this->getRequest()->getControllerName() );
		$logger->setEventItem('action', $this->getRequest()->getActionName() );
		$logger->setEventItem('date', Third_Funcs::getDate('now','datetime') );
		$logger->setEventItem('ip', $userInfos['REMOTE_ADDR']);
		$logger->setEventItem('host', $userInfos['HTTP_HOST']);
		$logger->setEventItem('referer',  $referer);
		$logger->setEventItem('params', Zend_Debug::dump( $this->getRequest()->getParams(),'Dados Postados', false) );
		$logger->setEventItem('tabela', $tabela );
		$logger->setEventItem('tabela_objeto_id', $tabela_objeto_id );

		$logger->info( $mensagem );
	}
	/**
	 * FORMATA URL CASO A CHAMADA SEJA FEITA 
	 * PARA UMA ACTION DO PROPRIO CONTROLLER
	 * @param $url
	 * @return string $url
	 */
	public function formatControllerUrl($url) {
		
		if (! eregi ( "http://", $url ) && ! eregi ( "https://", $url ) && ! eregi ( '/', $url )) {
			$url = $this->controller_url . '/' . $url;
		}
		return $url;
	}
	
	/**
	 * FUNCOES DE LISTAGENS
	*/
	public function getGridOptions(){
		$grid = array();

		if(isset($this->configs->grid ) )
			$grid = $this->configs->grid->options->toArray();
		
		return $grid;  
	}
	
	public function getColumns(){
		$columns = array();
		
		if(isset($this->configs->list->columns) )
			$columns = $this->configs->list->columns->toArray();

		$columns['gridEditOptions'] = array(
			'name'=>'Options',
			'index'=>'gridEditOptions',
			'width'=>'94'
		);

		return $columns; 
	}
	
	protected function isAdmin(){
		if( $this->_logged->nivel == 'superadmin' || $this->_logged->nivel == 'admin' )
			return true;

		return false;
	}

	protected function isSuperAdmin(){
		if( $this->_logged['nivel'] == 'superadmin')
			return true;

		return false;
	}
	
	protected function flash($message, $status, $goToUrl )
	{
		$this->_flashMessenger->addMessage( 
			array('message'=>$message, 'status'=>$status)
		);
		$this->_redirector->gotoUrl( $goToUrl );
	}
	
	/* CONTROLLERS */
	
	function getControllerName( $file ){
		 
		 $cont = @end(explode(DIRECTORY_SEPARATOR, realpath( $file ) ) );
		 
		 $controller = @reset(explode("Controller.php", $cont));

		 if( $controller != "Base" && $controller != "Error" && $controller != "Default" )
		 	return $controller;
	}

	/**
	 * Retorna estrutura do sistema
	 * @return unknown_type
	 */
	function getControllersDoSistema(){

		// TENTA RETORNAR DADOS DA ESTRUTURA DO CACHE
		if(!$estrutura = $this->cache->load('grupo_estrutura_sistema' )) {
			$this->cache->clean( 
    				Zend_Cache::CLEANING_MODE_MATCHING_TAG,
					array('grupos', 'privilegios')
			);

			$modules = Zend_Registry::get('registered_modules');
			$estrutura = array();

			$filter = new Zend_Filter_Word_CamelCaseToDash();

			foreach( $modules as $module=>$path ){
				$controllersDirectory = realpath( $this->_frontController->getControllerDirectory( $module ) );
	
				$files = new Third_Files( $controllersDirectory );
				
				$controllers = $files->getEntitiesList();
				foreach( $controllers as $ctrl ){
					$ctrl = realpath( $ctrl );
					
					if( strpos($ctrl, 'Controller.php') ){
						$controllerName = $this->getControllerName( $ctrl );
						if( $controllerName ){
								$controller = $this->getActionFromController( $ctrl );
								$estrutura[$module][$controllerName]['name'] = $filter->filter( $controller['name'] );
								$estrutura[$module][$controllerName]['menu'] = $controller['menu'];
								$estrutura[$module][$controllerName]['desc'] = $controller['desc'];
								$estrutura[$module][$controllerName]['label'] = $controller['label'];
								$estrutura[$module][$controllerName]['menu_secao'] = $controller['menu_secao'];
								$estrutura[$module][$controllerName]['controllers'] = $controller['actions'];
						}
					}
				}
			}
			
			$this->cache->save($estrutura, 'grupo_estrutura_sistema', array('grupos', 'privilegios') );
		}

		return $estrutura;
	}
	
	/**
	 * Retorna Actions do Controller
	 */
	function getActionFromController( $filename ){
		require_once( $filename );
		$r = new Zend_Reflection_File( $filename );

		$classes = $r->getClasses();
		$className = $classes[0]->name;
		
		$classReflection = new Zend_Reflection_Class( $className );

		$filter = new Zend_Filter_Word_CamelCaseToDash();
		
		// NOME E SECAO DO MENU DA CLASSE
			$name = $this->getItemTag( $classReflection, 'name' );
			$descricao = $classReflection->getDocblock()->getShortDescription();
			$menu = $this->getItemTag( $classReflection, 'menu' );
			$menu_secao = $this->getItemTag( $classReflection, 'menu_secao' );
			$label = $this->getItemTag( $classReflection, 'label' );
			$order = $this->getItemTag( $classReflection, 'order' );
			
			$classe['name'] = $name;
			$classe['desc'] = $descricao;
			$classe['menu'] = $menu;
			$classe['label'] = $label;
			$classe['menu_secao'] = $menu_secao;
			$classe['order'] = $order;

		//ACTIONS DA CALSSE
		$methodsAll = (  $classReflection->getMethods() );
		$methods = array();

		foreach( $methodsAll as $method ){
			
			if( preg_match( '/^Action/', substr($method->name,-6) ) ){
				$metData = array();
				$name = strtolower( $filter->filter( @substr($method->name, 0, strpos($method->name, "Action")) ) );

				$metData['name'] = $name;
				$metData['desc'] = $method->getDocblock()->getShortDescription();

				$menu = $method->getDocblock()->getTag('menu');
				if( $menu ) $menu = trim( $menu->getDescription() );
				$metData['menu'] = $menu;
				
				$methods[$name] = $metData;
			}
		}

		$classe['actions'] = $methods; 
		return $classe;
	}

	function getItemTag( $object, $tag ){
			$name = $object->getDocblock()->getTag( $tag );
			if( $name )
				$name = $name->getDescription();
			else $name = "";
			return trim($name);
	}
	
	function getEnumItensArray( $field ){
		$dataArray = array();
		try{
			$metadata = $this->dao->info('metadata');
			$fieldData = $metadata[ $field ]['DATA_TYPE'];
			$tipoArray  = "[".Third_Funcs::entre( $fieldData, 'enum(',')')."]";
			$tipoArray = str_replace("'",'"', $tipoArray );
			$tipoArray = Zend_Json::decode( $tipoArray );
			
			foreach( $tipoArray as $t ){
				$dataArray[$t] = $t;
			}
		} catch( Zend_Exception $e){
			echo $e->getMessage();	
		}
		
		return $dataArray;
	}
}

?>